package com.wyh.controller.groupfour.proprietor;

import com.wyh.common.result.Result;
import com.wyh.common.utils.SubStringFourUtils;
import com.wyh.domain.vo.gruopfour.customerVO.MyTicket;
import com.wyh.service.appservice.MyTicketService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

//我的票据
@RestController
@RequestMapping("/myticket")
@Api(tags = "我的票据")
public class MyTicketController {
    @Autowired
    private MyTicketService myTicketService;

    @ApiOperation("我的票据")
    @GetMapping("/customer")
    public Result<List<MyTicket>> getInvoiceRecordsByCustomerId(
            @RequestParam("客户id") int customerId,
            @RequestParam("类型：0发票|1收据") int type,
            @RequestParam(value = "页码", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "条数", defaultValue = "10") Integer pageSize
    ) {

        List<MyTicket> myTickets = myTicketService.findInvoiceRecordsByCustomerId(customerId, type, pageNum, pageSize);
        if (myTickets == null && myTickets.isEmpty()) {
            return Result.error();
        } else {
            return Result.success(myTickets);
        }
    }

    @GetMapping("/downloadFile")
    @ApiOperation("下载文件")
    public void downloadCheck(HttpServletRequest request, HttpServletResponse response) {
//        String urlStr = "https://big-lb.oss-cn-beijing.aliyuncs.com/a.pdf";
        String urlStr = request.getParameter("urlStr");
//        String fileName = "downloaded_file.pdf"; // 设定下载时显示的文件名
        String fileName = SubStringFourUtils.subStringAfterNthSlashFromEnd(urlStr, 1,'/'); // 设定下载时显示的文件名

        try {
            // 创建URL对象
            URL url = new URL(urlStr);

            // 打开连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法为GET
            connection.setRequestMethod("GET");

            // 准备输出流
            OutputStream os = response.getOutputStream();

            // 设置响应头
            response.setCharacterEncoding("utf-8");
            // 根据文件实际类型设置ContentType，这里假设是pdf
            response.setContentType("application/pdf");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

            // 通过连接获取输入流
            InputStream is = connection.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);

            // 缓冲区读取和写入数据
            byte[] buff = new byte[1024];
            int bytesRead;
            while ((bytesRead = bis.read(buff)) != -1) {
                os.write(buff, 0, bytesRead);
            }
            os.flush(); // 确保所有数据都写入输出流

            // 关闭流
            bis.close();
            is.close();
            os.close();
            connection.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
            // 如果发生异常，返回服务器内部错误
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }


    @GetMapping("/previewCheck")
    @ApiOperation("预览")
    public void previewCheckFromUrl(HttpServletRequest request,HttpServletResponse response) {
        Logger logger = LoggerFactory.getLogger(getClass());
        String urlStr = request.getParameter("urlStr");
        try {
            URL url = new URL(urlStr);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法为GET
            connection.setRequestMethod("GET");

            // 检查HTTP响应码是否成功
            int responseCode = connection.getResponseCode();
            if (responseCode != HttpURLConnection.HTTP_OK) {
                logger.error("Failed to get file from URL: {}, HTTP error code: {}", urlStr, responseCode);
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                return;
            }

            // 设置响应头
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/pdf");

            try (InputStream inputStream = connection.getInputStream();
                 OutputStream outputStream = response.getOutputStream()) {

                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
                outputStream.flush();
            }
        } catch (Exception e) {
            logger.error("Error occurred while processing the request for URL: {}", urlStr, e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
}
